# -*- coding: utf-8 -*-

from django import forms
from django.forms.models import inlineformset_factory, formset_factory
from django.shortcuts import get_object_or_404

from models import Pregao, ItemPregao, Item, Proposta
from utils.widgets import DateTimeWidgetUI, CustomDateWidget
from utils.validators import valida_dt_inicial_dt_final

class AbrirPregaoForm(forms.ModelForm):
    class Meta:
        model = Pregao
        fields = ('dt_inicio', 'dt_fim', 'dt_divulgacao')
        widgets = { 'dt_fim': DateTimeWidgetUI(),
                    'dt_inicio': DateTimeWidgetUI(),
                    'dt_divulgacao': CustomDateWidget(),
                    }

    def clean_dt_divulgacao(self):
        dt = self.cleaned_data['dt_divulgacao']
        if dt < self.cleaned_data['dt_fim'].date():
            raise forms.ValidationError(u'A data de divulgação deve ser maior que a data final do pregão.')
        return dt

    def clean(self):
        valida_dt_inicial_dt_final(self.cleaned_data['dt_inicio'], self.cleaned_data['dt_fim'])
        return self.cleaned_data

class ItensPregaoForm(forms.ModelForm):
    class Meta:
        model = ItemPregao
        fields = ('descricao', 'quantidade','prazo_entrega')

    descricao = forms.CharField(label='Item')


    def save(self, *args, **kwargs):
        descricao = self.cleaned_data['descricao']
        item, created = Item.objects.get_or_create(descricao=descricao)
        self.instance.item = item

        return super(ItensPregaoForm, self).save(*args, **kwargs)

ItensPregaoFormset = inlineformset_factory(Pregao, ItemPregao, form=ItensPregaoForm, exclude=('item'), extra=1)


class LanceForm(forms.ModelForm):
    class Meta:
        model = Proposta
        fields = ('item','valor')
        widgets = {'item': forms.HiddenInput()}
